const { uuidv4 } = require('../utils/string-utils')
/**
 * 基础model
 */
function BaseModel(client) {
  const vm = this
  vm.fieldDesc = [] // 字段描述
  let strType = ['uuid', 'text']
  /**
   * 增加
   */
  vm.addItem = function () {}
  /**
   * 批量新增
   */
  vm.addItems = function (obj) {
    return new Promise((resolve, reject) => {
      let valueList = []
      let fieldList = Object.keys(this.fields)
      let primaryKeyList = fieldList.filter(
        (item) => this.fields[item].isPrimary
      )
      let str = fieldList.join(',')
      fieldList.forEach((field) => {
        if (primaryKeyList.includes(field)) {
          valueList.push(`'${uuidv4()}'`)
        } else {
          let v = strType.includes(this.fields[field].type)
            ? `'${obj[field]}'`
            : obj[field] || ''
          valueList.push(v)
        }
      })
      let sql = `insert into ${
        this.tableName
      } (${str}) values (${valueList.join(',')})`
      client
        .query(sql)
        .then((res) => {
          if (res.rowCount) {
            resolve(res.rowCount)
          }
        })
        .catch((err) => {
          reject(err)
        })
    })
  }
  /**
   * 查询
   * @param {*} page 页码
   * @param {*} pageSize 一页多少条
   */
  vm.query = function ({ page, pageSize, where }, opt) {
    return new Promise((resolve, reject) => {
      let str = Object.keys(this.fields).join(',')
      let sql = `select ${str} from ${this.tableName} ${where}`
      if (opt && opt.printSql) {
        console.log('sql', sql)
      }
      client.query(sql).then((res) => {
        let data = res.rows
        let total = res.rowCount || 0
        resolve({
          data,
          total
        })
      }).catch(err => {
        reject(err)
      })
    })
  }
  /**
   * 删除一项
   * @param {*} keyMap
   */
  vm.removeItem = function (keyMap) {}

  vm.removeItems = function () {}
}

module.exports = BaseModel
